package com.imooc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.imooc.enums.ImageTypes;
import com.imooc.mapper.SpiderNoMapper;
import com.imooc.pojo.SaveModel;
import com.imooc.pojo.SpiderNoModel;
import com.imooc.service.DumpFileService;
import com.imooc.utils.ExcelUtils;
import com.imooc.utils.FileUtils;
import com.imooc.utils.URLFecter;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Log4j2
public class DumpFileServiceImpl implements DumpFileService {
    @Autowired
    private ExcelUtils excelUtils;
    @Autowired
    private SpiderNoMapper spiderNoMapper;
    private final int DIR_NAME = 10000;
    private String imageUrl = "https://www.coupang.com/vp/products/%s/items/%s/vendoritems/%s";

    @Override
    public int saveSpiderNo(SpiderNoModel spiderNoModel) {
        return spiderNoMapper.saveSpiderNo(spiderNoModel);
    }

    @Override
    public SpiderNoModel getSpiderNo(String spiderNoModel) {
        SpiderNoModel spiderNoModel1 = spiderNoMapper.getSpiderNo(spiderNoModel);
        return spiderNoModel1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Integer> exportDownLoad(HttpServletResponse response, String url, String procectId, int splitNumD, List<SaveModel> list, Map<String, Integer> param) {
        try {
            Map<String, String> header = new HashMap<>();
            header.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36");
            header.put(":authority", "www.coupang.com");
            header.put(":method", "GET");
            header.put(":scheme", "https");
            header.put("accept", "*/*");
            header.put("accept-encoding", "gzip, deflate, br");
            header.put("origin", "https://store.coupang.com");
            header.put("referer", "https://store.coupang.com");
            JSONObject object = null;
            try {
                object = URLFecter.getMethod(url, header);
            } catch (Exception e) {
                e.printStackTrace();
            }
            JSONArray products = object.getJSONObject("data").getJSONArray("products");
            JSONObject product;
            Map<String, String> pheader;
            SpiderNoModel spiderNoModel;
            for (Object ob : products) {
                int splitNum = param.get("splitNum");
                String customerDir = String.valueOf(param.get("pageStartNo") + param.get("pageNo"));
                if (param.get("limitNum") < 1) {
                    break;
                }
                product = JSONObject.parseObject(ob.toString());
                if (null != spiderNoMapper.getSpiderNo(product.getString("productId"))) {
                    continue;
                }
                pheader = new HashMap<>();
                pheader.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36");
                pheader.put(":authority", "www.coupang.com");
                pheader.put(":method", "GET");
                pheader.put(":scheme", "https");
                pheader.put("accept", "*/*");
                pheader.put("accept-encoding", "gzip, deflate, br");
                pheader.put("origin", "https://store.coupang.com");

                pheader.put("referer", "https://store.coupang.com");
                spiderNoModel = new SpiderNoModel();
                spiderNoModel.setProductId(product.getString("productId"));
                try {
                    list.addAll(URLFecter.URLParser(pheader, product.getString("link"), product.getString("productId"), customerDir));
                    downLoadImage(product, header, customerDir);
                    // 保存节点信息
                    spiderNoMapper.saveSpiderNo(spiderNoModel);
                    param.put("splitNum", param.get("splitNum") - 1);
                } catch (Exception e) {
                    log.error(e.getMessage());
                } finally {
                    if (param.get("splitNum") == 0 || param.get("limitNum") == 0) {
                        try {
                            if (list.size() > 0) {
                                param.put("pageNo", param.get("pageNo") - 1);
                                // excel下载
                                String excelPath = System.getProperty("user.dir") + "\\download\\" + customerDir + "\\";
                                FileUtils.mkdirs(excelPath);
                                excelUtils.writeExcel(excelPath + "结果.xlsx", "工作簿1", list);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } finally {
                            param.put("splitNum", splitNumD);
                            list.clear();
                        }
                    } else {
                        param.put("splitNum", splitNum - 1);
                        System.out.println(param.get("splitNum"));
                    }
                    param.put("limitNum", param.get("limitNum") - 1);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return param;
    }

    /**
     * 图片下载
     *
     * @param product
     * @param pheader
     * @param procectId
     */
    private void downLoadImage(JSONObject product, Map<String, String> pheader, String procectId) {
        JSONObject images;
        String path = System.getProperty("user.dir") + "\\download\\" + procectId + "\\" + product.getString("productId") + "\\";
        String image;
        try {
            images = URLFecter.getMethod(String.format(imageUrl, product.getString("productId"), product.getString("itemId"), product.getString("vendorItemId")), pheader);
            FileUtils.mkdirs(path);
            List<String> iList = new ArrayList<>();
            for (Object detail : images.getJSONArray("details")) {
                if (JSON.parseObject(detail.toString()).getString("contentType").equals("IMAGE_NO_SPACE")) {
                    iList.add("http:" + JSON.parseObject(detail.toString()).getJSONArray("vendorItemContentDescriptions").getJSONObject(0).getString("content"));
                } else if (JSON.parseObject(detail.toString()).getString("contentType").equals("TEXT") || JSON.parseObject(detail.toString()).getString("contentType").equals("HTML")) {
                    iList.addAll(URLFecter.urlParseImage(JSON.parseObject(detail.toString()).getJSONArray("vendorItemContentDescriptions").getJSONObject(0).getString("content")));
                }
            }
            for (int i = 5; i < 5 + iList.size(); i++) {
                try {
                    image = iList.get(i - 5);
                    FileUtils.downLoadImage(path + i + "." + getImageType(image), image);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getImageType(String image) {
        for (ImageTypes imageTypes : ImageTypes.values()) {
            if (image.equals(imageTypes.getType())) {
                return imageTypes.getType();
            }
        }
        return ImageTypes.JPG.getType();
    }


//    @Override
    @Transactional(rollbackFor = Exception.class)
    public void spiderMatch(HttpServletResponse response, String url) {
            Map<String, String> header = new HashMap<>();
    }

    private Map<String, String> getHeader(Map<String, String> header){
        header.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36");
        header.put(":method", "GET");
        header.put(":scheme", "https");
        header.put("accept", "*/*");
        return header;
    }
}
